package com.zjs.controller;

import com.zjs.common.utils.MD5Utils;
import com.zjs.mapper.SysUserMapper;
import com.zjs.pojo.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping(value = "sysUser")
public class SysUserDemo {




    private static final Logger logger = LoggerFactory.getLogger(SysUserDemo.class);




    @Autowired
    SysUserMapper sysUserMapper;




    @RequestMapping(value = "login.action")
    public String LoginUser(String username, String password, @RequestParam  String checkcode, HttpServletRequest request, HttpServletResponse response) {



        //首先 验证 验证码是否正确
        //通过session得到需要输入的正确的验证码
        String key = (String) request.getSession().getAttribute("key");

        // TODO: 2019/12/16
        
        //如果不正确则返回登录页面
        if (checkcode.contains(key) && null!=checkcode){


            Subject subject = SecurityUtils.getSubject();


            UsernamePasswordToken token=new UsernamePasswordToken(username, MD5Utils.text2md5(password));

            try{

                subject.login(token);

                //如果 认证成功
                if (subject.isAuthenticated()){


                    //得到 JSESSIONID
                    String id = request.getSession().getId();

                    //创建需要更新的对象 将浏览器的SessionId 存储到 对应的对象上
                    SysUser user=new SysUser();
                    user.setUsername(username);
                    user.setIsLogin(id);

                    sysUserMapper.upIsLoginCode(user);


                    //存取session

                    request.getSession().setAttribute("user",username);


                    //清除清除session
                    request.getSession().removeAttribute("msg");

                }

                return "common/index";

            }catch (Exception e){

                logger.info("登录失败,用户名:{},错误信息:{}",username,e.getMessage());

                request.getSession().setAttribute("msg","登录失败,请重新输入用户名和密码!");

                return "redirect:/login.jsp";

            }


        }



            request.getSession().setAttribute("msg","登录失败,请重新输入用户名和密码!");


            return "redirect:/login.jsp";

    }




}
